package edu.bw.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理器中封装开启事务、提交事务、回滚事务、释放资源(均是通过当前线程的连接操作)
 */
@Component
public class TransactionManager {

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private ThreadLocal<Connection> threadLocal;
    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            connectionFactory.currentThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionFactory.currentThreadConnection().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionFactory.currentThreadConnection().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 释放资源:就是释放数据库连接(将连接重新放回连接池)
     */
    public void release(){
        try {
            connectionFactory.currentThreadConnection().close();
            threadLocal.remove();//将数据库连接与当前线程解绑,这里解绑后的连接还可以与其他绑定,防止不同线程绑定同一个连接
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }





}
